<?php
/**
*用户订阅比赛的业务逻辑处理事件
*@author susy.liang<liangling@ilongyuan.com.cn>
*/

namespace Api\Event;

class RaceScribeEvent extends BaseEvent 
{
	protected $modelObj ;

	/**
	*基础参数初始化
	*/
	protected function _initialize(){
		parent::_initialize();
		$this->modelObj = D('Common/RaceScribe', 'Service');
	}

	/** 
	 * 获取用户的订阅列表
	 * @param  $uid int 用户标识; 
	 * @param  $detail boolen 是否只返回race_id 数组
	 * @param  $p int 页码 默认所有
	 * @param  $limit 个数限制 默认所有
	 * @return 
	 */
	public function mine($uid, $detail = false, $p=0, $limit=0)
	{
		$map = array('uid'=>intval($uid));
		$res = $this->modelObj->where($map);
		$p && $res = $res->page($p);
		$limit && $res = $res->limit($limit);
		$raceIds = $res->order('race_time desc')->getField('race_id', true);

		if (!$detail){
			return $raceIds;
		}else{
			$rgEvent = A('Api/RaceGroup','Event');
			foreach ($raceIds as $raceId) {
				$race = $rgEvent->info($raceId, true);
				$race['score'] && $race['score'] = explode('-', $race['score']);
				$race['is_scribe'] = 1;
				$data[$raceId] = $race;
			}
			return $data;
		}
	}


	/** 
	 * 获取用户订阅数
	 * @param $uid int 用户标识
	 * @return int
	 */
	
	public function count_mine($uid)
	{
		return $this->modelObj->where(array('uid'=>intval($uid)))->count();
	}


	/** 
	 * 是否订阅
	 * @param $uid int 用户标识
	 * @param $raceId 比赛标识
	 * @return 
	 */
	
	public function is_scribe($uid, $raceId)
	{
		if (!$uid || !$raceId){
			return false;
		}

		$map = array(
				'uid'=>intval($uid),
				'race_id'=>intval($raceId)
			);
		return $this->modelObj->where($map)->count() > 0;
	}


	/** 
	 * 添加订阅
	 * @param $uid int 用户标识
	 * @param  $raceId 比赛标识
	 * @return 
	 */
	public function scribe($uid, $raceId)
	{
		if(!$uid || !$raceId){
			return false;
		}

		$map = array(
				'uid'=>intval($uid),
				'race_id'=>intval($raceId)
			);
		if(!$this->is_scribe($uid, $raceId))
		{
			$map['create_time'] = NOW_TIME;
			$race = event('RaceGroup')->info($raceId);
			$map['race_time']   = $race['race_time'];
			$res = $this->modelObj->add($map);
			if($res)
			{
				A('Api/RaceGroup', 'Event')->scribe($raceId);
			}	
			return ture;
		}
		return false;		
	}


	/** 
	 * 取消订阅
	 * @param $uid int 用户标识
	 * @param  $raceId 比赛标识
	 * @return 
	*/
	public function unscribe($uid, $raceId)
	{
		if (!$uid || !$raceId)
		{
			return;
		}

		$map = array(
				'uid'=>intval($uid),
				'race_id'=>intval($raceId)
			);
		if ($this->modelObj->where($map)->find())
		{
			$res = $this->modelObj->where($map)->delete();	
			if ($res)
			{
				A('Api/RaceGroup', 'Event')->scribe($raceId, false);
			}
			return true;
		}
		return false;
	}

}